package 网络编程.udp;



import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author Y·C
 * @version 1.0.0
 * @ClassName UDPReceiverA.java
 * @Description UDP接收端A
 * @createTime 2023年05月04日 08:47:00
 */
public class UDPReceiverA {
    public static void main(String[] args) throws IOException {
        //1.创建一个DatagramSocket 对象，准备在9999接收数据
        DatagramSocket socket = new DatagramSocket(9999);
        //2.构建一个DatagramPackage对象，，准备接收数据 UDP 数据包最大64k
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        //3.调用接收方法，将通过网络传输的DatagramPacket对象
        //填充到packet对象
        System.out.println("接收端A 等待接收数据...");
        socket.receive(packet);
        //4.可以把packet进行拆包，取出数据，并显示
        int length = packet.getLength();//实际接收到的数据字节长度
        byte[] data = packet.getData();//接收到的数据
        String s = new String(data, 0, length);
        System.out.println(s);

        //====回复====
        data = "好的，明天见".getBytes();
        packet = new DatagramPacket(data, data.length, InetAddress.getByName("192.168.17.1"), 9998);
        socket.send(packet);


        socket.close();
        System.out.println("A端退出");
    }
}
